package replaceStringUtil;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class StringReplaceString02 {

	List<String> des = new ArrayList<String>();
	List<String> sou = new ArrayList<String>();
	List<String> my = new ArrayList<String>();

	public static void main(String[] args) {
		StringReplaceString02 srs = new StringReplaceString02();
		srs.readfile();
		srs.replaceString("SmsSeleniumUtil.assertTrue(SmsSeleniumUtil.isDisplayed(SmsSeleniumUtil.getCachedElement(SmsSROListPageUtil.", 
				")));", "public final static By", " = By.");
		srs.writeString();
		System.out.println("替换已经完成!");
	}

	private void readfile() {
		File file1 = new File("F:/截取.txt");
		File file2 = new File("F:/替换.txt");
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader(file1));
			while (br.ready()) {
				String s = br.readLine();
				des.add(s.trim());
			}

			br = new BufferedReader(new FileReader(file2));
			while (br.ready()) {
				String s = br.readLine();
				sou.add(s.trim());
			}

		} catch (IOException e) {
			System.out.println("replace err...");
			e.printStackTrace();
		} finally {
			try {
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	private void replaceString(String startDes, String endDes, String startSou,
			String endSou) {
		if (des.size() != 0 && sou.size() != 0) {
			for (int i = 0; i < des.size(); i++) {
				if (des.get(i).startsWith(startSou) && des.get(i).contains(endSou)) {
					String[] start = des.get(i).split(startSou);
					String[] end = start[1].split(endSou);
					if (sou.get(i).startsWith(startDes)	&& sou.get(i).endsWith(endDes)) {
						my.add(startDes + end[0].trim() + endDes);
					}
				}
			}
		}
	}
	
	private void writeString() {
		File file = new File("F:/替换后的文本.txt");
		if (file.exists()) {
			file.delete();
			file = new File("F:/替换后的文本.txt");
			file = new File("F:/a.txt");
		}
		BufferedWriter bw = null;
		try {
			bw = new BufferedWriter(new FileWriter(file));
			bw.write("assertTrue: " + "\r" + "\n");
			bw.write("\r");
			bw.write("\n");
			
			for (int i = 0; i < my.size(); i++) {
				bw.write(my.get(i));
				bw.write("\r");
				bw.write("\n");
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				bw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
